package com.zhixun.mobile.modules.site.web.shopping;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;

import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.AssertUtils;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.zhixun.mobile.common.utils.EncryptUtils;
import com.zhixun.mobile.common.utils.RequestUtil;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.sys.utils.SessionMemberUtils;

/**  
* @author Administrator  
*    
*/
@Controller
@RequestMapping(value= Global.FRONT_PATH+ "/site/shopping")  /* site */
public class MicroShoppingController extends BaseController {
	
	private final Logger logger = Logger.getLogger(MicroShoppingController.class);
	@Autowired
	SystemService systemService;
	
	@Autowired
	WechatDaoHelper wechatDaoHelper;
	
	
	@Autowired
	private WechatMemberService wechatMemberService;
	
	
	@Autowired
	private WeChatService weChatService;

	

	/**
	 * 登陆后跳转
	 *@author xiaoqian
	 * @param product
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * 2014-10-21上午10:37:10
	 */
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String uid = request.getParameter("uid");
		
		String mobile = request.getParameter("mobile");
		String pwd = request.getParameter("pwd");
		Long pid=RequestUtil.getLong(request, "productId");
		Long fid=RequestUtil.getLong(request, "flowerId");
		
		WechatMember member = null;
		WechatMember wechatMember =null;
		member = isLogin(request,uid);
		boolean login = false;
		if (AssertUtils.notNull(member)) {
			login = true;
		}
		if (member == null) {
			List<WechatMember> memberList = wechatMemberService.getMembersByMobile(new User(Long.parseLong(uid)),
					mobile);
			if(memberList!=null && memberList.size()==1){
				wechatMember=memberList.get(0);
			}else{
				model.addAttribute("mobile", mobile);
				if(memberList==null||memberList.size()==0){
					model.addAttribute("errormessage", " 您还没有注册!请到平台进行注册");
				}
				if(memberList.size()>=1){
					model.addAttribute("errormessage", "该手机号绑定了多个账号，为了安全请联系管理员！！");
				}
				if(pid!=null){
					return "redirect:/f/site/shopping/toLogin?productId="+pid;
				}else if(fid!=null){
					return "redirect:/f/site/shopping/toLogin?flowerId="+fid;
				}else{
					return "redirect:/f/site/shopping/toLogin?uid="+uid;
				}
			}
			if ( wechatMember != null) {
					login = EncryptUtils.validatePassword(pwd,
							wechatMember.getPassword());
				// /登录
				if (login) {
					SessionMemberUtils.addSessionValue(request,
							"member_" + new User(Long.parseLong(uid)), wechatMember);
				}
			} else {
				login = false;
			}
		}
		if(login){
			if(pid!=null){
				return "redirect:/f/site/shopping/viewProduct/"+pid+".html?uid="+wechatMember.getUser().getId()+"&wechatId="+wechatMember.getWechatId();
			}else if(fid!=null){
				return "redirect:/f/site/shopping/viewFlower/"+fid+".html?uid="+wechatMember.getUser().getId()+"&wechatId="+wechatMember.getWechatId();
			}else{
				return "redirect:/f/site/shopping/toUserCentre?uid="+wechatMember.getUser().getId()+"&wechatId="+wechatMember.getWechatId();
			}
		}

		model.addAttribute("mobile", mobile);
		model.addAttribute("errormessage", "您的手机号或密码不正确!");
		if(pid!=null){
			return "redirect:/f/site/shopping/toLogin?productId="+pid;
		}else if(fid!=null){
			return "redirect:/f/site/shopping/toLogin?flowerId="+fid;
		}else{
			return "redirect:/f/site/shopping/toLogin?uid="+uid;
		}
	}
	

	

	/**
	 * 判断用户是否登陆
	 *
	 * @return WechatMember null 没有登陆 ；
	 */
	//TODO 判断用户是否登陆
	public WechatMember isLogin(HttpServletRequest request, String uid) {

		String wechatId = request.getParameter("wechatId");
		User user=new User(Long.valueOf(uid));

		wechatMemberService.clear();
		
		WechatMember member = SessionMemberUtils.getSessionMemberByUserId(request, uid);
		//WechatMember member = null;
		if(member!=null){
			return member;
		}else{
			member = wechatMemberService.getByWechatMemberId(user, wechatId);
			if (member != null ) {
				SessionMemberUtils.addSessionValue(request,"member_" + uid, member);
			}
			return member;
		}
		
	}
	
	
	/**
	 * 获取主题目录
	 *@author xiaoqian
	 * @param project
	 * @return
	 * 2014-10-18下午1:31:19
	 */
	public String getProjectTheme(){
		return "default";
	}
	

	/**
	 * 跳到登陆页面前根据 uid 和 wechatID 查询 会员。 如果有， 返回 手机号
	 */
	public Map<String, Object> beforeLogin(String uid, String wechatId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String mobile = "";
		String pwd = "";

		User user = new User();

		user.setId(Long.valueOf(uid));

		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(
				user, wechatId);

		if (AssertUtils.notNull(wechatMember)) {

			mobile = wechatMember.getMobile();

			// 是否需要初始化密码
			if (StringUtils.isEmpty(wechatMember.getPassword())
					|| wechatMember.isRandomPassword()) {
				pwd = com.thinkgem.jeesite.common.utils.StringUtils
						.getRandPassword();
				String enpwd = EncryptUtils.MD5EncodeString(pwd);
				wechatMember.setPassword(enpwd);
				wechatMember.setIsRandomPassword(true);

				wechatMemberService.save(wechatMember);
			}

			if (AssertUtils.isNullOrEmpty(pwd)) {
				pwd = null;
			}

			map.put("mobile", mobile);
			map.put("pwd", pwd);
		}

		return map;
	}
	
	
	/**
	 * 购物车添加商品
	 *@author xiaoqian
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * 2014-11-4下午5:43:26
	 */
	public Boolean addPruduct(Long id,HttpServletRequest request,HttpServletResponse response){
		String products = CookieUtils.getCookie(request, "shoppingCart");
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		Map<String, Object> maps = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(products)){
			maps = JSON.parseObject(products);
			if(maps!=null){
				Integer count = (Integer) maps.get(id+"");
				if(count==null){
					maps.put(id+"", 1);
				}else{
					maps.put(id+"", count+1);
				}
			}
		}else{
			maps.put(id+"", 1);
		}
		
		
		CookieUtils.setCookie(response, "shoppingCart", JsonMapper.getInstance().toJson(maps));
		return true;
	}
	
	
	

	/**
	 * 获得oauth路径     url传入    /site/shopping
	 * @param url
	 * @param uid
	 * @param request
	 * @return
	 */
	public String getOAuthUrl(String url,String uid,HttpServletRequest request,HttpServletResponse response){

		String path = request.getContextPath();
		String basePath  = request.getScheme()+"://"+request.getServerName()+path;

		WeChat weChat =  weChatService.getWeChatByUserId(Long.parseLong(uid));
		String state = uid;
		url = url.replace("null", "");
		CookieUtils.setCookie(response, "redirectUrl", basePath+Global.getFrontPath()+url);
		
		System.out.println(basePath);

		String redirectUrl =URLEncoder.encode(basePath+"/f/oauth/redirect");

		String returnUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+weChat.getAppId()+"&" +
				"redirect_uri="+redirectUrl+"&response_type=code&" +
				"scope=snsapi_base&state="+state+"&connect_redirect=1#wechat_redirect";
		return returnUrl;
	}
	
	/**
	  * 获得验签名的数据
	  * @param map
	  * @return
	  * @throws Exception 
	  */
	 @SuppressWarnings("unchecked")
	private String getVerifyData(Map map) {
	     String service = (String) ((Object[]) map.get("service"))[0];
	     String v = (String) ((Object[]) map.get("v"))[0];
	     String sec_id = (String) ((Object[]) map.get("sec_id"))[0];
	     String notify_data = (String) ((Object[]) map.get("notify_data"))[0];
	     System.out.println("通知参数为："+"service=" + service + "&v=" + v + "&sec_id=" + sec_id + "&notify_data="+ notify_data);
	     return "service=" + service + "&v=" + v + "&sec_id=" + sec_id + "&notify_data="
	            + notify_data;
	 }
	

    @RequestMapping(value="toPromoteQrCode")
    public String toPromoteQrCode(HttpServletResponse response,HttpServletRequest request,Model model){
    	String uid =request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		String ticket = request.getParameter("ticket");
		WechatMember member =isLogin(request,uid );
		if (AssertUtils.isNull(member)) {
			String url = getOAuthUrl("/site/shopping/toPromoteQrCode?a=1",uid,request,response);
			return "redirect:"+url;
		}
		
		model.addAttribute("ticket", ticket);
		model.addAttribute("member", member);
		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
    	return "modules/site/themes/default/toPromoteQrCode";
    }
    
    
    
    /**
     * 修改个人资料
     * @param request
     * @param response
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "doUpdatePersonInformation")
	public String doUpdatePersonInformation(HttpServletRequest request,HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) {
    	String uid =request.getParameter("uid");
		String wechatId = request.getParameter("wechatId");
		if(StringUtils.isBlank(uid)){
			return null;
		}
		
		WechatMember member =isLogin(request,uid );
		if (AssertUtils.isNull(member)) {
			String url = getOAuthUrl("/site/shopping/doUpdatePersonInformation?uid="+uid+"&wechatId="+wechatId,uid,request,response);
			return "redirect:"+url;
		}
		
		model.addAttribute("member", member);
		model.addAttribute("uid", uid);
		model.addAttribute("wechatId", wechatId);
		
    	return "modules/site/themes/default/updatePersonInformation";
	}

	// ----修改个人资料
	//TODO 修改个人资料处理
	@RequestMapping(value = "updatePersonInformation")
	public String updatePersonInformation(HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		
		String uid = request.getParameter("uid"); // userId
		
		String wechatId = request.getParameter("wechatId"); // OpenId

		String sex = request.getParameter("sex");
		String birthday = request.getParameter("birthday");
		String mobile = request.getParameter("mobile");
		String name = request.getParameter("name");
		String mid = request.getParameter("mid");
		String IDCardNumber = request.getParameter("IDCardNumber");
		String email = request.getParameter("email");

		System.out.println("sex" + sex);

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", uid);
		model.addAttribute("topage", "dopayPassword");

		WechatMember member = this.isLogin(request, uid);

		if (AssertUtils.isNull(member)) {
			String url = getOAuthUrl("/site/shopping/updatePersonInformation?uid="+uid+"&wechatId="+wechatId,uid,request,response);
			return "redirect:"+url;
		}
		
		if(StringUtils.isNotEmpty(mobile)){
			if(StringUtils.isEmpty(member.getMobile())){
				ScoreUtils.addScore(member, 1000, "1","完善个人资料，送1个消费积分");
			}
		}
		member.setName(name);
		member.setSex(sex);
		member.setBirthday(birthday);
		member.setMobile(mobile);
		member.setIDCardNumber(IDCardNumber);
		member.setEmail(email);
		wechatMemberService.save(member);
		model.addAttribute("message", "您的用户信息修改成功！！！");
		model.addAttribute("member", member);
		this.updateMemberSession(request, uid, member);
		return "redirect:/f/site/shopping/toUserCentre?uid="+uid+"&wechatId="+wechatId;

	}
		// 更新session中用户信息
	public void updateMemberSession(HttpServletRequest request, String uid,WechatMember member) {
			SessionMemberUtils.addSessionValue(request, "member_" + uid, member);
	}
    
}


